package cn.git.agent.enhance;

import cn.git.agent.loader.InterceptorInstanceLoader;
import net.bytebuddy.implementation.bind.annotation.AllArguments;
import net.bytebuddy.implementation.bind.annotation.RuntimeType;
import net.bytebuddy.implementation.bind.annotation.This;

/**
 * @description: 构造方法拦截器
 * @program: bank-credit-sy
 * @author: lixuchun
 * @create: 2024-12-25
 */
public class ConstructorMethodsInterceptor {

    /**
     * 静态方法环绕通知器
     */
    private ConstructorMethodAroundInterceptor aroundInterceptor;

    /**
     * 构造方法
     *
     * @param interceptorClassName
     * @param classLoader
     */
    public ConstructorMethodsInterceptor(String interceptorClassName,
                                         ClassLoader classLoader) {
        try {
            aroundInterceptor = InterceptorInstanceLoader.load(interceptorClassName, classLoader);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("获取构造方法拦截器失败 ConstructorMethodsInterceptor");
        }
    }

    /**
     * 被标注 RuntimeType 注解的方法就是拦截方法，此时返回的值与返回参数可以与被拦截的方法不一致
     * byteBuddy会在运行期间给被拦截的方法参数进行赋值
     * @return
     */
    @RuntimeType
    public Object intercept(@This Object obj,
                            @AllArguments Object[] allArguments) throws Throwable {

        Object call = null;
        try {
            EnhancedInstance instance = (EnhancedInstance) obj;
            aroundInterceptor.onConstruct(instance, allArguments);
        } catch (Throwable t) {
            t.printStackTrace();
        }

        return call;
    }
}
